<?php
if (!defined('KAIZEKU')) exit(42);
/**
 * WP-iStalker Chrome Min 
 * Scripts Handler
 * 
 * PHP 5
 * 
 * @package	WordPress
 * @subpackage	wp-istalker-chrome-min
 * 
 * @category	Template
 * @author	Avice (ChaosKaizer) De'vereux <ck+wp-istalker-min@istalker.net>
 * @author	NH. Noah <noah+wp-istalker-min@kakkoi.net>
 * @copyright 	2007 - 2009 Avice De'vereux, NH. Noah
 * @license 	http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU General Public License v2 
 * @version 	CVS: $Id: script.php 13 2009-01-11 15:22:40Z chaoskaizer $
 * @since 	0.1
 */

/**
 * wpiStyle
 * @uses $wp_styles WP_styles object (BackPress Scripts enqueue)
 * @since 0.1
 */
final class wpiScript
{
	/**
	 * Template scripts url
	 * 
	 * @access	public
	 * @var		string
	 */			
	public $uri;
		
	/**
	 * WP filter id
	 * @var int
	 */
	public $wp_filter_id;

	/**
	 * Registered script to be load
	 * 
	 * @access	public
	 * @var		mixed|array
	 */		
	public $js;

	/**
	 * Default theme's' scripts
	 * store all scripts handle name
	 * @access	public
	 * @var		mixed|array
	 */		
	public $scripts;

	/**
	 * WP hierachical section
	 * store scripts for specific sections
	 * @access	public
	 * @var		mixed|array
	 */		
	public $section;

	/**
	 * Loop procedure counter
	 * @access	private
	 * @var		int
	 */	
	private $_flag;

	/**
	 * WordPress full url with trailing slash
	 * 
	 * @see		$wp_scripts WP_Scripts object
	 * @access	public
	 * @var		string
	 */			
	public $base_url;
	
	/**
	 * Store array list of wpiScript error message
	 *	 
	 * @access	public
	 * @var		mixed|array
	 */		
	public $errors;
	

	public function __construct()
	{	global $wp_scripts;

		foreach(array('js','scripts','section','errors') as $meta) $this->$meta = array(); 
		
		if ( !is_a($wp_scripts, 'WP_Scripts') ){
			$wp_scripts = new WP_Scripts();	
		}		
		
		$this->base_url = $wp_scripts->base_url;
		$this->build = date('Ymd',SV_CURRENT_TIMESTAMP);
		$this->combine_handle = wpiTheme::H_PREFIX.'js-combine';
					
		$this->_registerScript($wp_scripts);
		
		add_action('wp_head',array($this,'printScript'),wpiTheme::LAST_PRIORITY+9);
	}
	
	
	/**
	 * wpiStyle::_registerScript()
	 * 
	 * Register all theme stylesheet	 
	 * 
	 * @uses	$wp_scripts WP_Scripts object
	 * @access	private
	 * @since	0.1
	 * 
	 * @param	mixed|object $deps WP_styles object 
	 */
	private function _registerScript($deps)
	{ 
		if ( ($js = wpi_get_dir(WPI_JS_DIR, wpiTheme::JS_FILE_REGEX)) != false){
			
			if (has_count($js)){
				
				foreach($js as $file){
					$this->scripts[] = $handle = wpiTheme::H_PREFIX.str_rem('.js',$file);
					$deps->add($handle, self::relativeUrl($file, $deps->base_url), array('combine' => true), $this->build);
				}
				
				unset($js, $file, $handle, $build);
				
				$this->setFlag(1)->defaultScripts();
			}
						
		} else {
			
			// proceed to download and retry
			$this->_jsAPIsLibraries();
			$this->_registerScript($deps);		
		}
	}
	
	
	/**
	 * @link http://code.google.com/apis/ajaxlibs/
	 */
	private function _jsAPIsLibraries()
	{		
		$js_libs = array();
		
		$js_libs['jquery'] = array(
							'version' => '1.2.6',
							'type' => 'compressed',
							'uri' => 'http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js');
							
		$js_libs['jquery-ui'] = array(
							'version' => '1.5.3',
							'type' => 'compressed',
							'uri' => 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.3/jquery-ui.min.js');							
							
		$js_libs['swfobject'] = array(
							'version' => '2.1',
							'type' => 'compressed',
							'uri' => 'http://ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js');
		
		$js_libs = apply_filters(wpiFilter::JS_API_LIBS, $js_libs);
		
		if (has_count($js_libs)){
			
			if (true == WP_Http_Fopen::test() ){
				$Http = new WP_Http_Fopen();
			} elseif (true == WP_Http_Curl::test() ){
				$Http = new WP_Http_Curl();
			} elseif (true == WP_Http_ExtHttp::test() ){
				$Http = new WP_Http_ExtHttp();
			}			
			
			$options = array(
				'methods' => 'GET',
				'user-agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5'
			);
			
			$cnt = count($js_libs);
			if ($cnt >= 2) $options['timeout'] = (5 * ($cnt + 1));
			
			$this->content = array();
			
			foreach($js_libs as $meta => $script){
				
				$response = $Http->request($script['uri'], $options);
				
				if (has_count($response)){		
					$content = $response['body'];
					$response = null;
							
					wpi_fwrite(WPI_JS_DIR.$meta.'.js', $content);
							
					unset($file, $content, $response);
				} else {
					$this->errors[] = __METHOD__.' failed';
					$this->errors[] = $response;				
				}
			}	
			
			unset($Http);							
		}			
	}
	
	
	/**
	 * void wpiScript::defaultScripts()
	 * register default theme scripts
	 * 
	 * @uses $wp_scripts WP_Scripts object (WP_Dependecies script enqueue API)
	 * @see wpiFilter::DEFAULLT_SCRIPTS 
	 * @since 0.1
	 */
	public function defaultScripts()
	{	global $wp_scripts;
		
		// if not ready return
		if ($this->_flag <= 0) return;
		
		$scripts = array('jquery', 'jquery-ui');
		$enqueue = array();
		 		
		/**
		 * filter: wpiFilter::DEFAULT_SCRIPTS
		 */
		$scripts = apply_filters(wpiFilter::DEFAULT_SCRIPTS, $scripts);
		
		if (has_count($scripts)){			
			
			$js = array_flip($this->scripts);
			
			foreach($scripts as $i){
				$handle = wpiTheme::H_PREFIX.$i;
			
				if (isset($js[$handle])){
					$this->section[wpiSection::K_ALL][] = $i; 	
					$enqueue[] = $i.'.js';	
				}												
			}
			
			$src = array_str($enqueue); // join/implode all the lists
			
			$wp_scripts->add($this->combine_handle, self::relativeUrl($src,$this->base_url), array('combine'=>'true', 'handle'=> $this->section[wpiSection::K_ALL]), $this->build);
			$this->setFlag(2);							
		}
		
		unset($scripts,$js);
	}
	
	
	public function isReady($tag='jquery'){
		$scripts = array_flip($this->scripts);		
		return (isset($scripts[wpiTheme::H_PREFIX.$tag]));			
	}
	
	
	/**
	 * void public wpiScript::printScript()
	 * print queue Script 
	 * 
	 * @uses $wp_script WP_Script object
	 * @since 0.1
	 */	
	public function printScript()
	{	global $wp_scripts;
		
		if (!is_a($wp_scripts,'WP_Scripts')){
			$wp_scripts = new WP_scripts();		
		}
		
		$wp_scripts->do_item($this->combine_handle);
					
		$this->setFlag(3);
	}
		
	
	/**
	 * public wpiScript::setFlag()
	 * set conditional procedure flag number 
	 * for debugging purpose
	 * @param mixed|int	$int Number
	 * @return pointer current object
	 */
	public function setFlag($int)
	{
		$this->_flag = (int) $int;	
		return $this;
	}
			
	
	public function dump()
	{	global $wp_scripts;
		wpi_dump($wp_scripts);
	}
	
	
	/**
	 * static wpiScript::relativeUrl()
	 * Make link relative to WP_CONTENT_URL
	 * 
	 * @uses	$wp_scripts	WP_Script object
	 * @since	0.1
	 * @param	string $filename The js filename
	 * @param	string $base_url Wordpress URL  
	 * @return	string Relative js URL from wp-content URL
	 * 
	 */
	public static function relativeUrl($filename, $base_url= false)
	{
		if (!$base_url){
			global $wp_scripts;
			$base_url = $wp_scripts->base_url;		
		}
		
		return str_rem($base_url, WPI_THEME_URL.$filename);		
	}

	
	public function __destruct(){ unset($this); }
	
	
	private function __clone(){}	
}				
?>